import axios from 'axios';
import store from '@/store/index';
import { API } from '../api/api';
import { message } from 'ant-design-vue';
import { notification } from 'ant-design-vue';

// 创建axios实例
const service = axios.create({
  baseURL: API.domain, // axios中请求配置有baseURL选项，表示请求URL公共部分
  headers: API.headers,
  timeout: 10000, // 超时
});
// request拦截器
service.interceptors.request.use(
  (config) => {
    config.headers['uid'] = store.getters['user/uid'];
    config.headers['token'] = store.getters['user/token'];
    return config;
  },
  (error) => {
    console.log(error);
    Promise.reject(error);
  },
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    if (res.data.code == 'error') {
      message.error(res.data.message);
    } else {
      //请求成功
      if (res.data.message != null && res.data.message != '') {
        message.success(res.data.message);
      }
    }
    return res.data;
  },
  (error) => {
    console.log('err-->' + error);
    let { message } = error;
    if (message == 'Network Error') {
      message = '接口网络连接异常';
    } else if (message.includes('timeout')) {
      message = '接口请求超时';
    } else if (message.includes('Request failed with status code')) {
      message = '接口' + message.substr(message.length - 3) + '异常';
    }
    notification.error({
      message: '接口异常',
      description: message,
    });
    return Promise.reject(error);
  },
);

export default service;
